<script setup lang="ts">
import {
  postMemberAddressAPI,
  getMemberAddressByIdAPI,
  putMemberAddressByIdAPI,
} from '@/services/address'
import { onLoad } from '@dcloudio/uni-app'
import { useAddressStore, useMemberStore, useStore } from '@/stores'

import { ref, onMounted, nextTick } from 'vue'

import { calculateDistance } from '@/utils/http'
import { expectOrderAPI } from '@/services/order'
// import BaiduMap from './map.vue'
const { getUserInfo } = useMemberStore()

const { getStoreInfo } = useStore()

const { getAddress, changeSelectedAddress, setDeliveryPrice } = useAddressStore()

// 接收页面参数
const query = defineProps<{
  id: string
  delivery: number | string
}>()
// 表单数据
const form = ref({
  id: '',
  userId: '',
  receiver: '', // 收货人
  contact: '', // 联系方式
  fulllocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
  latitude: '', // 纬度
  longitude: '', // 经度
})
// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  receiver: {
    rules: [{ required: true, errorMessage: '请输入收货人姓名' }],
  },
  contact: {
    rules: [
      { required: true, errorMessage: '请输入联系方式' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
    ],
  },
  fulllocation: {
    rules: [{ required: true, errorMessage: '请选择所在地区' }],
  },
  address: {
    rules: [{ required: true, errorMessage: '请选择详细地址' }],
  },
}

// 获取收货地址详情数据
const getMemberAddressByIdData = async () => {
  // 有 id 才调用接口
  if (query.id) {
    // 发送请求
    const res = await getMemberAddressByIdAPI(query.id)
    // 把数据合并到表单中
    Object.assign(form.value, res.data)
  }
}

// 页面加载
onLoad(() => {
  getMemberAddressByIdData()
})
// 动态设置标题
uni.setNavigationBarTitle({ title: query.id ? '修改地址' : '新建地址' })

// 收集所在地区
const onRegionChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 省市区(前端展示)
  form.value.fulllocation = ev.detail.value.join(' ')
  // 省市区(后端参数)
  const [provinceCode, cityCode, countyCode] = ev.detail.code!
  // 合并数据
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}

// 收集是否默认收货地址
const onSwitchChange: UniHelper.SwitchOnChange = (ev) => {
  form.value.isDefault = ev.detail.value ? 1 : 0
}
// 获取表单组件实例，用于调用表单方法
const formRef = ref<UniHelper.UniFormsInstance>()
// 提交表单
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value?.validate?.()
    // 校验通过后再发送请求
    Object.assign(form.value, { userId: getUserInfo()?.id })
    if (query.id) {
      Object.assign(form.value, { id: query.id })
      // 修改地址请求
      await putMemberAddressByIdAPI(form.value)
    } else {
      // 新建地址请求
      await postMemberAddressAPI(form.value)
    }

    if (form.value.isDefault === 1) {
      expectOrderCost()
    }

    // 成功提示
    uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 400)
  } catch (error) {
    uni.showToast({ icon: 'error', title: '请填写完整信息' })
  }
}

// 路线费用
const expectOrderCost = async () => {
  if (!query.delivery || query.delivery === 'null' || query?.delivery === 1) {
    return
  }
  // 门店经纬度
  const storeInfo: any = getStoreInfo()
  const startPointLongitude = storeInfo.longitude
  const startPointLatitude = storeInfo.latitude
  // 配送地址经纬度
  const address: any = getAddress()
  const endPointLongitude = address.longitude
  const endPointLatitude = address.latitude

  const expectOrderRes = await expectOrderAPI({
    startPointLatitude,
    startPointLongitude,
    endPointLatitude,
    endPointLongitude,
  })
  setDeliveryPrice(expectOrderRes.data.feeRuleResponseVo.totalAmount)
}

const showMap = ref(false)
const addAddressMap = () => {
  showMap.value = true
  init()
}

// import Header from '@/pagesMember/address/header.vue'
const systemInfo = uni.getSystemInfoSync()
const { safeAreaInsets, windowHeight, screenWidth } = systemInfo
// rpx 转 px 工具函数
const rpxToPx = (rpx: number) => (rpx / 750) * screenWidth

// 初始高度（800rpx）
const initialMainHeight = rpxToPx(800)

// 响应式地图高度
const mainHeight = ref(initialMainHeight)
const mapLoaded = ref(true)

// ======== 滚动事件处理 ========
const onScrolltolower = () => {
  const listTargetRpx = 1000
  const listHeightPx = rpxToPx(listTargetRpx)

  // 计算新地图高度：窗口高 - 列表高
  mainHeight.value = Math.max(windowHeight - listHeightPx, 200)

  // 重建地图
  mapLoaded.value = false
  nextTick(() => {
    setTimeout(() => {
      mapLoaded.value = true
    }, 50)
  })
}

const scrolltoupper = () => {
  // 还原初始高度
  mainHeight.value = initialMainHeight

  // 重建地图
  mapLoaded.value = false
  nextTick(() => {
    setTimeout(() => {
      mapLoaded.value = true
    }, 50)
  })
}
const close = () => {
  showMap.value = false
}
const submit = () => {
  detailInfo.value.address = markers.value[0].address
  detailInfo.value.latitude = markers.value[0].latitude
  detailInfo.value.longitude = markers.value[0].longitude

  form.value = { ...form.value, ...detailInfo.value }
  changeSelectedAddress(form.value)

  showMap.value = false
}

const addressMap = ref('')
const markers = ref({} as any)

const setMarkers = (res: any) => {
  markers.value = res.map((item: any) => {
    return {
      title: item.address, // 标记点名称（可选，部分平台显示在 infoWindow）
      address: item.address, // 自定义字段，非标准 marker 属性（可用于传递数据）
      alpha: 1, // 透明度，1 表示不透明（合法值）
      width: 30, // 图标宽度（单位 px）
      height: 30, // 图标高度
      id: item.id, // ✅ 修正：原为 'tiem.id'，应为 'item.id'
      latitude: item.latitude, // 纬度（必须）
      longitude: item.longitude, // 经度（必须）
      iconPath: '../../static/img/red_marker.png', // 图标路径（建议使用绝对路径或本地资源）
      iconTapPath: '../../static/img/red_marker.png', // 点击后的图标（可选）
    }
  })
}

// 引入百度地图API

const bmap = require('../../static/js/bmap-wx.min.js')
const BMapWX = bmap.BMapWX
//    这个地方是你在百度地图中申请的ak
var BMap = new BMapWX({ ak: 'hOtF9JR4wCD5SSQGKhddv4IsHildEpVF' })

const detailInfo = ref<any>({
  latitude: null,
  longitude: null,
  address: '',
})

const poisList = ref([] as any[])

const init = () => {
  if (!detailInfo.value.latitude || !detailInfo.value.longitude) {
    uni.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: (data: any) => {
        detailInfo.value.latitude = data.latitude
        detailInfo.value.longitude = data.longitude
        getCurrentLocation(detailInfo.value)
      },
    })
  } else {
    getCurrentLocation(detailInfo.value)
  }
}

const getCurrentLocation = (e: any) => {
  const { latitude, longitude } = e
  if (!latitude || !longitude) return
  // 调用reverseGeocode方法进行反向地理编码
  BMap.regeocoding({
    location: `${latitude},${longitude}`,
    coordtype: 'gcj02ll', // 输入坐标是 GCJ-02 火星坐标
    ret_coordtype: 'gcj02ll', // 返回结果也使用 GCJ-02 坐标
    radius: 1000, // 搜索半径 1000 米
    success: (data: any) => {
      console.log('成功:', data)

      poisList.value = data.originalData.result.pois.map((item: any) => {
        return {
          ...item,
          address: item.addr,
          longitude: item.point.x,
          latitude: item.point.y,
        }
      })
      setMarkers(data.wxMarkerData)
      console.log(markers.value)
      // 成功回调处理逻辑
    },
    fail: (data: any) => {
      console.error('失败:', data)
      // 失败回调处理逻辑
    },
  })
}

const markertap = (info: any) => {
  // const storeId = markers.value.find((v:any) => v.id === info.detail.markerId)?.storeId
  // uni.navigateTo({ url: '/pagesStore/detail/detail?id=' + storeId })
}

const searchMap = (e: any) => {
  const query = e.value.trim()
  if (!query) return
  activeIndex.value = 0
  BMap.suggestion({
    query: query,
    coordtype: 'gcj02ll', // 输入坐标是 GCJ-02 火星坐标
    ret_coordtype: 'gcj02ll', // 返回结果也使用 GCJ-02 坐标
    output: 'json',
    success: (data: any) => {
      poisList.value = data.result.map((item: any) => ({
        name: item.name,
        address: item.address || '',
        latitude: item.location.lat,
        longitude: item.location.lng,
        uid: item.uid,
        distance: calculateDistance(
          detailInfo.value.latitude,
          detailInfo.value.longitude,
          item.location.lat,
          item.location.lng,
        ),
      }))
    },
    fail: (err: any) => {
      console.error('失败：', err)
      wx.showToast({ title: '搜索失败', icon: 'none' })
    },
  })
}

const activeIndex = ref(0)
const checkhandler = (record: any, index: number) => {
  activeIndex.value = index
  console.log(record)

  detailInfo.value.latitude = record.latitude
  detailInfo.value.longitude = record.longitude

  markers.value = [record].map((item: any, idx: number) => {
    return {
      title: item.address, // 标记点名称（可选，部分平台显示在 infoWindow）
      address: item.address, // 自定义字段，非标准 marker 属性（可用于传递数据）
      alpha: 1, // 透明度，1 表示不透明（合法值）
      width: 30, // 图标宽度（单位 px）
      height: 30, // 图标高度
      id: idx, // ✅ 修正：原为 'tiem.id'，应为 'item.id'
      latitude: item.latitude, // 纬度（必须）
      longitude: item.longitude, // 经度（必须）
      iconPath: '../../static/img/red_marker.png', // 图标路径（建议使用绝对路径或本地资源）
      iconTapPath: '../../static/img/red_marker.png', // 点击后的图标（可选）
    }
  })

  console.log(markers.value)
}
</script>

<template>
  <view class="content">
    <!-- <BaiduMap/> -->
    <uni-forms :rules="rules" :model="form" ref="formRef">
      <!-- 表单内容 -->
      <uni-forms-item name="receiver" class="form-item">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </uni-forms-item>
      <uni-forms-item name="contact" class="form-item">
        <text class="label">手机号码</text>
        <input
          class="input"
          placeholder="请填写收货人手机号码"
          :maxlength="11"
          v-model="form.contact"
        />
      </uni-forms-item>
      <uni-forms-item name="fulllocation" class="form-item">
        <text class="label">所在地区</text>
        <picker
          class="picker"
          @change="onRegionChange"
          mode="region"
          :value="form.fulllocation.split(' ')"
        >
          <view v-if="form.fulllocation">{{ form.fulllocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="address" class="form-item">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
        <text class="iconfont icon-logistics-tracking" @click="addAddressMap"></text>
      </uni-forms-item>
      <view class="form-item">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          color="#4CAF50"
          @change="onSwitchChange"
          :checked="form.isDefault === 1"
        />
      </view>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <!-- <button class="button">保存并使用</button> -->
  <button @tap="onSubmit" class="button">保存并使用</button>

  <view v-if="showMap" class="wrap-page" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="top">
      <view class="cancel" @click="close">取消</view>
      <view class="address-text">
        {{ detailInfo.address || '' }}
      </view>
      <view
        class="confirm"
        @click="submit"
        :style="{ backgroundColor: true ? 'rgba(0, 0, 0, 0.2)' : '#42b983' }"
        >确定</view
      >
    </view>
    <!-- <Header :title="'个人中心'" /> -->

    <scroll-view class="wrap-scroll" scroll-y :show-scrollbar="false" enable-back-to-top>
      <view class="wrap-main" :style="{ height: mainHeight + 'px' }">
        <map
          class="map"
          id="map"
          style="width: 100%; height: 100%"
          :latitude="detailInfo.latitude"
          :longitude="detailInfo.longitude"
          :scale="14"
          :show-location="false"
          :markers="markers"
          @markertap="markertap"
        ></map>
      </view>
      <view class="wrap-list">
        <view class="search-input">
          <uni-search-bar
            radius="5"
            placeholder="请输入关键词"
            clearButton="auto"
            cancelButton="none"
            @confirm="searchMap"
          />
        </view>
        <scroll-view
          class="primary"
          scroll-y
          :show-scrollbar="false"
          enable-back-to-top
          @scrolltoupper="scrolltoupper"
          @scrolltolower="onScrolltolower"
        >
          <view
            class="list-item"
            @tap="checkhandler(item, index)"
            v-for="(item, index) in poisList"
            :key="index"
          >
            <view class="item-con">
              <view class="item-address">{{ item.address }}</view>
              <view class="item-info">
                <view class="distance">{{ item.distance }}m</view>
                <view>|</view>
                <view class="name">{{ item.name }}</view>
              </view>
            </view>
            <view class="item-checked" v-if="activeIndex === index">
              <text class="iconfont icon-gouxuan2"></text>
            </view>
          </view>
        </scroll-view>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}
.wrap-page {
  display: flex;
  flex-direction: column;

  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
  .top {
    position: absolute;
    width: 100%;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 40rpx;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
    z-index: 999;

    .confirm {
      height: 60rpx;
      line-height: 60rpx;
      padding: 0 20rpx;
      border-radius: 10rpx;
      background-color: #42b983;
    }

    .address-text {
      width: 55vw;
      text-align: center;
      overflow: hidden;
      word-wrap: break-word;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }

  .wrap-scroll {
    .wrap-main {
      width: 100%;
      height: 800rpx;
    }
    .wrap-list {
      height: 1000rpx;
      display: flex;
      flex-direction: column;
      .search-input {
        padding: 0 20rpx;
      }
      .list-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        padding: 20rpx;
        border-bottom: 1px solid $border-color;
        .item-con {
          flex: 1;
          display: flex;
          flex-direction: column;
          .item-address {
            font-size: $font-size;
          }
        }

        .item-checked {
          display: flex;
          justify-content: center;
          align-items: center;
          .icon-gouxuan2 {
            color: $color;
          }
        }

        .item-info {
          padding-top: 20rpx;
          display: flex;
          flex-direction: row;

          justify-content: flex-start;
          font-size: $font-size;
          color: #333;

          .distance,
          .name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .distance {
            color: #888;
            font-size: $font-size;
          }

          .name {
            color: #888;
            font-weight: 500;
            flex: 1;
            font-size: $font-size;
          }

          // 分隔线
          > view:nth-child(2) {
            color: #ddd;
            font-size: $font-size;
          }
        }
      }
    }
  }
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: $color;
}
</style>
